<?php
/**
 * 文件描述
 * Created on 2021/8/12 13:53
 * Create by LZH
 */

namespace App\Service\Admin;

use App\Model\Admin\AdminModel;
use App\Service\BaseService;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;

class LoginService extends BaseService
{
    /**
     * 用户登录
     * @return array|false
     * @author LZH
     */
    public function login($login_ip, $login_time)
    {
        $username = $this->getRequestParam('username');
        $password = $this->getRequestParam('password');

        // 这里需要绕过模型get/all查询方法，因为这两个方法会自动添加school_code字段，但登陆的时候是不知道这个字段的
        $builder = new QueryBuilder();
        $builder->setPrefix(DB_PREFIX)->where('username', $username)->getOne('admin');
        $ret = DbManager::getInstance()->query($builder, false);
        $builder->reset();
        $userInfo = $ret->getResultOne();

        if (empty($userInfo)) {
            return false;
        }
        if (!password_verify($password.$username, $userInfo['password'])) {
            return false;
        }

        $builder->where('id', $userInfo['id'])->update('admin', [
            'login_ip' => $login_ip,
            'login_time' => $login_time
        ]);
        $ret = DbManager::getInstance()->query($builder, false);
        $result = $ret->getResult();

        if ($result) {
            return $userInfo;
        }
        return false;
    }
}
